package com.coollang.smartbra.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;

import com.andexert.library.RippleView;
import com.coollang.smartbra.MyAutoLayoutActivity;
import com.coollang.smartbra.R;
import com.coollang.smartbra.base.ActionFragment;
import com.coollang.smartbra.base.MyApplication;
import com.coollang.smartbra.bleutil.BleSendUtils;
import com.coollang.smartbra.bleutil.BleUtil;
import com.coollang.smartbra.bleutil.callback.BleCallbackImpl;
import com.coollang.smartbra.constant.Constants;
import com.coollang.smartbra.dialog.RunSetDialog;
import com.coollang.smartbra.eventbus.CommonEvent;
import com.coollang.smartbra.fragment.ActionCountFragment;
import com.coollang.smartbra.fragment.PbzcFragment;
import com.coollang.smartbra.model.ActionDataModel;
import com.coollang.smartbra.presenter.ActionActivityPresenter;
import com.coollang.smartbra.utils.ActivitySwitcher;
import com.coollang.smartbra.utils.DisplayUtils;
import com.coollang.smartbra.utils.LockTimerUitls;
import com.coollang.smartbra.utils.MyAnimationDrawable;
import com.coollang.smartbra.utils.TimeUtils;
import com.coollang.smartbra.utils.TranslucentSystemBarUtils;
import com.coollang.smartbra.utils.UIUtils;
import com.inuker.bluetooth.library.Code;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;


// 具体动作页面
public class ActionActivity extends MyAutoLayoutActivity implements RippleView.OnRippleCompleteListener {

    private static final String TAG = ActionActivity.class.getSimpleName();
    @BindView(R.id.status_bar)
    View mStatusBar;
    @BindView(R.id.rv_back)
    RippleView mRvBack;
    @BindView(R.id.tv_title)
    TextView mTvTitle;
    @BindView(R.id.iv_right)
    ImageView mIvRight;
    @BindView(R.id.rl_top)
    RelativeLayout mRlTop;
    @BindView(R.id.content)
    FrameLayout mContent;
    @BindView(R.id.action_frame_videoview)
    VideoView mVideoview;
    @BindView(R.id.action_frame)
    FrameLayout mFLAction;
    @BindView(R.id.linearlayout_title)
    LinearLayout mLayoutTitle;
    @BindView(R.id.heart_imag)
    ImageView mIvHeartTooHeight;

    String[] actionName = {"", "深蹲", "深蹲跳", "仰卧起坐", "卷腹", "俯卧撑", "平板支撑"};
    int[] videos = new int[]{R.raw.sdt, R.raw.sdt, R.raw.ywqz, R.raw.jf, R.raw.fwc, R.raw.pbzc};
    int[] videos1 = new int[]{R.raw.sdt1, R.raw.sdt1, R.raw.ywqz1, R.raw.jf1, R.raw.fwc1, R.raw.pbzc1};

    private int mType;
    /**
     * 是否在运动
     */
    private boolean isRunning;

    private ActionFragment mFragment;

    /**
     * 运动开始时间
     */
    private long startTimeUnix;
    private long endTimeUnix;

    //***********************************************数据相关*******************************************//
    private List<String> upTimesList = new ArrayList<>();//分动作上升时间
    private List<String> downTimesList = new ArrayList<>();//分动作下降时间
    private List<Integer> heartRateIntList = new ArrayList<>();//心率集合
    private List<String> numsList = new ArrayList<>();//第几个的索引
    /**
     * 运动的个数
     */
    private int nums;
    /**
     * 平板支撑时长
     */
    long length;

    protected int i = 0;
    private Handler mHandler;

    private ActionActivityPresenter mPresenter;
    private MediaPlayer mMediaPlayer;
    private Random mRandom;

    @Override
    protected void initView() {
        setContentView(R.layout.activity_action);
        ButterKnife.bind(this);
        // instance = this;
        // 设置沉浸式状态栏
        TranslucentSystemBarUtils.showChenJinZhuangTaiLan(mStatusBar, this, mContent);
        EventBus.getDefault().register(this);
        initViews();
        initListener();

        // 开启心率开关
        BleUtil.getInstance().sendData((byte) 0x47);
        mRandom = new Random();
    }

    /**
     * 初始化各种View
     */
    private void initViews() {
        Intent intent = getIntent();
        mType = intent.getIntExtra("type", 1) + 1;

        //设置下面布局
        getSupportFragmentManager()
                .beginTransaction()
                .replace(R.id.action_frame, getFragment(mType))
                .commit();

        //设置标题
        mTvTitle.setText(actionName[mType]);
        mTvTitle.setTextColor(getResources().getColor(R.color.black_666));

        // 播放视频
        // playVideo(mType);

        mIvRight.setBackgroundResource(R.drawable.run_setting);
    }

    private void initListener() {
        mRvBack.setOnRippleCompleteListener(this);
    }

    @Override
    protected void initData() {
        mHandler = new Handler();
        // mMediaPlayer = new MediaPlayer();
        mMediaPlayer = MediaPlayer.create(this, R.raw.voice_count_1);
        mPresenter = new ActionActivityPresenter(this);
        mPresenter.getUserStrength();
    }

    @Override
    protected void onStart() {
        super.onStart();

        // 播放视频
        if (!isRunning) {
            playVideo(mType);
        } else {
            playVideo1(mType);
        }

        BleUtil.getInstance().registerNotifyListener(mBleCallback);
    }

    @Override
    protected void onPause() {
        super.onPause();
        mVideoview.stopPlayback();
    }

    @Override
    protected void onDestroy() {

        // 关闭心率开关
        BleUtil.getInstance().sendData((byte) 0x47, (byte) 02);
        BleUtil.getInstance().unRegisterNotifyListener();
        EventBus.getDefault().unregister(this);
        isRunning = false;
        mHandler.removeCallbacksAndMessages(null);

        if (mMediaPlayer.isPlaying()) {
            mMediaPlayer.stop();
        }

        mMediaPlayer.release();

        super.onDestroy();
    }

    private Fragment getFragment(int type) {
        mFragment = null;

        if (type == 6) {
            mFragment = new PbzcFragment();
        } else {
            mFragment = new ActionCountFragment();
        }
        return mFragment;
    }

    /**
     * 运动开始前播放的视频
     */
    public void playVideo(int position) {
        mVideoview.setVideoURI(Uri.parse("android.resource://" + getPackageName() + "/" + videos[position - 1]));
        //让VideiView获取焦点
        mVideoview.start();
        mVideoview.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                mVideoview.start();
            }
        });
    }

    /**
     * 运动开始后播放的视频
     */
    public void playVideo1(int position) {
        mVideoview.setVideoURI(Uri.parse("android.resource://" + getPackageName() + "/" + videos1[position - 1]));
        //让VideiView获取焦点
        mVideoview.start();
        mVideoview.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                mVideoview.start();
            }
        });
    }

    public void onEventMainThread(CommonEvent event) {
        if (event.type == CommonEvent.UNLOCK) {
            // showStopTV();
        } else if (event.type == CommonEvent.START) {
            // 点击了 start 按钮
            switch (event.what) {
                case CommonEvent.REQUESTSUEECCD:
                    isRunning = true;
                    //开始运动时间
                    startTimeUnix = TimeUtils.getCurrentTimeUnixLong();

                    // 发送动作开始的命令
                    BleSendUtils.sendStartDataByPosition(mType);

                    mRvBack.setVisibility(View.GONE);
                    mFragment.startAction();
                    mFragment.actionStart();
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    public void onComplete(RippleView rippleView) {

        if (isRunning) {
            // 正在运动
            Toast.makeText(this, "请结束当前运动", Toast.LENGTH_SHORT).show();
        } else {
            finish();
        }
    }


    @OnClick({R.id.iv_right, R.id.iv_unwind})
    public void onClick(View view) {

        switch (view.getId()) {
            case R.id.iv_right:
                new RunSetDialog(this, false, mIvRight).show();
                break;
            case R.id.iv_unwind:
                // 横竖屏切换
                if (getScreenOrientation() == Configuration.ORIENTATION_PORTRAIT) {
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                    return;
                }
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                break;
            default:
                break;

        }
    }


    public void toFinish(int time) {

        if (mType == 6) {
            // 说明是平板支撑
            length = time;
            if (length < 10000) {
                showFinishDialog();
            } else {
                toFinishTwo();
            }
        } else {
            // 说明是其他动作
            if (nums < 10) {
                showFinishDialog();
            } else {
                toFinishTwo();
            }
        }
    }

    private void showFinishDialog() {

        AlertDialog dialog = new AlertDialog.Builder(this).create();
        dialog.setMessage(getString(R.string.no_countortimedata));
        dialog.setButton(DialogInterface.BUTTON_NEGATIVE, getString(R.string.continued), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();

                // 点击继续
                mFragment.continueAction();

            }
        });

        dialog.setButton(DialogInterface.BUTTON_POSITIVE, getString(R.string.tofinish), new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();

                BleSendUtils.sendEndDataByPosition(mType);
                LockTimerUitls.getInstance().stopTimer();
                finish();
            }
        });
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();

        Button posiviveButton = dialog.getButton(DialogInterface.BUTTON_POSITIVE);
        posiviveButton.setTextColor(Color.parseColor("#F79444"));
        Button negativeButton = dialog.getButton(DialogInterface.BUTTON_NEGATIVE);
        negativeButton.setTextColor(Color.parseColor("#000000"));
    }


    private void toFinishTwo() {
        BleSendUtils.sendEndDataByPosition(mType);
        //结束训练
        endTimeUnix = TimeUtils.getCurrentTimeUnixLong();

        saveActionData();

        LockTimerUitls.getInstance().stopTimer();

        ActivitySwitcher.goShareAct(this, mType);
    }

    /**
     * 计时
     */
    private void saveActionData() {

        ActionDataModel model = new ActionDataModel();
        model.setType(mType);
        model.setId(startTimeUnix);
        model.setStart_time(startTimeUnix);
        model.setEnd_time(endTimeUnix);

        if (heartRateIntList.size() == 0) {
            // 心率最大值
            model.setMax_rate(0);
            // 心率最小值
            model.setMin_rate(0);
            // 求平均值
            model.setAve_heart_rate(0);

        } else {
            // 心率最大值
            model.setMax_rate(Collections.max(heartRateIntList));
            // 心率最小值
            model.setMin_rate(Collections.min(heartRateIntList));
            // 求平均值
            model.setAve_heart_rate(getAve());
        }
        // 运动时间  计数

        if (mType != 6) {
            model.setNums(nums);
        } else {
            model.setNums(length);
        }

        // 保存到数据库中
        mPresenter.saveNumberActionData(model);
    }

    /**
     * 求平均值
     */
    private int getAve() {

        int sum = 0;
        int size = heartRateIntList.size();
        for (int i = 0; i < size; i++) {
            int number = heartRateIntList.get(i);
            sum += number;
        }

        return sum / size;
    }

    //*************************************上传逻辑**********************************************//

    /**
     * ====================================== 蓝牙监听
     */
    private BleCallbackImpl mBleCallback = new BleCallbackImpl() {
        @Override
        public void onBleConnected() {
            MyApplication.getApplication().sendDate();// 校准时间戳
        }

        @Override
        protected void onPBZCRecieved(int heartRate, int errorFlag, int errorType) {

            startOrStopAnimation(heartRate);

            mFragment.onPBZCRecieved(heartRate, errorFlag, errorType);

            // 保存心率
            saveHeartRate(heartRate);
        }

        //仰卧起坐
        @Override
        protected void onYWQZRecieved(long upTime, long downTime, int heartRate, int errorFlag, int errorType) {
            setCountDatas(upTime, downTime, heartRate, errorFlag, errorType);
        }

        //卷腹
        @Override
        protected void onJFRecieved(long upTime, long downTime, int heartRate, int errorFlag, int errorType) {
            setCountDatas(upTime, downTime, heartRate, errorFlag, errorType);
        }

        // 俯卧撑
        @Override
        protected void onFWCRecieved(long upTime, long downTime, int heartRate, int errorFlag, int errorType) {
            setCountDatas(upTime, downTime, heartRate, errorFlag, errorType);
        }

        // 深蹲跳
        @Override
        public void onSDTRecieved(long upTime, long downTime, int heartRate, int errorFlag, int errorType) {
            setCountDatas(upTime, downTime, heartRate, errorFlag, errorType);
        }


        @Override
        protected void onSDRecieved(long upTime, long downTime, int heartRate, int errorFlag, int errorType) {
            setCountDatas(upTime, downTime, heartRate, errorFlag, errorType);
        }

        @Override
        public void onActionZhengFan(byte zhengfan, byte qingxie) {
            if (alertDialog != null) {
                alertDialog.dismiss();
            }
            String message = "";

            if (zhengfan == 0 && qingxie == 0) {
                // 戴反也戴斜了
                message = "设备戴反也戴斜了,请调整设备";
            } else if (zhengfan == 0 && qingxie == 1) {
                // 戴反了
                message = "设备戴反了,请调整设备";
            } else if (zhengfan == 1 && qingxie == 0) {
                // 戴斜了
                message = "设备戴斜了,请调整设备";
            } else if (zhengfan == 1 && qingxie == 1) {
                // 设备戴正确
                message = "设备佩戴正确,请开始运动吧";
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        alertDialog.dismiss();
                    }
                }, 2000);
            }
            showDialog(message);
        }
    };


    AlertDialog alertDialog;

    private void showDialog(String message) {
        AlertDialog.Builder builder = new AlertDialog.Builder(ActionActivity.this);
        builder.setMessage(message);
        alertDialog = builder.show();
    }

    /**
     * @param errorFlag 错误标志位
     * @param errorType 错误类型
     */
    private void setCountDatas(long upTime, long downTime, int heartRate, int errorFlag, int errorType) {

        startOrStopAnimation(heartRate);

        mFragment.onActionCount(heartRate, errorFlag, errorType);
        setCountData(upTime, downTime, errorFlag, heartRate);
    }

    private void saveHeartRate(int heartRate) {

        if (heartRate != 0) {
            heartRateIntList.add(heartRate);
        }
    }

    private void setCountData(long upTimes, long downTimes, int errorFlag, int heartRate) {
        if (errorFlag != 0) {
            saveUpAndDown(upTimes, downTimes, errorFlag, heartRate);
        }
    }

    private void saveUpAndDown(long upTimes, long downTimes, int errorFlag, int heartRate) {
        upTimesList.add(upTimes + "");
        downTimesList.add(downTimes + "");
        saveHeartRate(heartRate);
        numsList.add(errorFlag + "");
        if (errorFlag == 1) {
            nums++;
        }
    }

    //***********************************声音播报**********************************************//

    public int getType() {
        return mType;
    }

    public String getErrorType(int errorType) {
        String type = "";
        switch (mType) {
            case 1:
                type = Constants.SD_ERROR_TYPE[errorType];
                break;
            case 2:
                type = Constants.SDT_ERROR_TYPE[errorType];
                break;
            case 3:
                type = Constants.YWQZ_ERROR_TYPE[errorType];
                break;
            case 4:
                type = Constants.JF_ERROR_TYPE[errorType];
                break;
            case 5:
                type = Constants.FWC_ERROR_TYPE[errorType];
                break;
            case 6:
                type = Constants.PBZC_ERROR_TYPE[errorType];
                break;
            default:
        }
        return type;
    }

    /**
     * 获取错误信息,以及播放音乐
     *
     * @param errorType
     * @return
     */
    public String getErrorInfo(int errorType) {
        String type = "";
        int voiceID = 0;
        switch (mType) {
            case 1:
                type = Constants.SD_ERROR_INFO[errorType];
                voiceID = Constants.SD_ERROR_VOICE[errorType];
                break;
            case 2:
                type = Constants.SDT_ERROR_INFO[errorType];
                voiceID = Constants.SDT_ERROR_VOICE[errorType];
                break;
            case 3:
                type = Constants.YWQZ_ERROR_INFO[errorType];
                voiceID = Constants.YWQZ_ERROR_VOICE[errorType];
                break;
            case 4:
                type = Constants.JF_ERROR_INFO[errorType];
                voiceID = Constants.JF_ERROR_VOICE[errorType];
                break;
            case 5:
                type = Constants.FWC_ERROR_INFO[errorType];
                voiceID = Constants.FWC_ERROR_VOICE[errorType];
                break;
            case 6:
                type = Constants.PBZC_ERROR_INFO[errorType];
                voiceID = Constants.PBZC_ERROR_VOICE[errorType];
                break;
            default:
                break;
        }
        playVoice(voiceID);
        return type;
    }

    public int getErrorVideo(int errorType) {
        int type = 0;
        return type;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == Code.REQUEST_SUCCESS) {
            if (requestCode == 821) {
                finish();
            }
        }
    }

    private void startOrStopAnimation(int heart) {
        if (heart > Integer.parseInt(MyApplication.mLogInDataBean.getHr_alarm())) {
            if (Integer.parseInt(MyApplication.mLogInDataBean.getIsalarm()) == 1) {
                startHeartAnimation();
            }
        } else {
            stopHeartAnimation();
        }
    }

    private void startHeartAnimation() {
        mIvHeartTooHeight.setVisibility(View.VISIBLE);
        startAnimation();
    }

    private void startAnimation() {
        MyAnimationDrawable.animateRawManuallyFromXML(R.drawable.heart_too_height,
                mIvHeartTooHeight, new Runnable() {
                    @Override
                    public void run() {
                        // 动画开始时回调

                    }
                }, new Runnable() {
                    @Override
                    public void run() {
                        // 动画结束时回调
                        if (mIvHeartTooHeight.getVisibility() == View.VISIBLE) {
                            startHeartAnimation();
                        }
                    }
                });
    }

    private void stopHeartAnimation() {
        mIvHeartTooHeight.setVisibility(View.GONE);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (getScreenOrientation() == Configuration.ORIENTATION_LANDSCAPE) {
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                return false;
            } else if (isRunning) {
                Toast.makeText(this, "请结束当前运动", Toast.LENGTH_SHORT).show();
                return false;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 横竖屏切换
     */
    private int getScreenOrientation() {
        return getResources().getConfiguration().orientation;
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        int value = getScreenOrientation();
        if (value == Configuration.ORIENTATION_LANDSCAPE) {
            // 全屏
            mFLAction.setVisibility(View.GONE);
            mLayoutTitle.setVisibility(View.GONE);
            setScreenLayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        } else if (value == Configuration.ORIENTATION_PORTRAIT) {
            // 半屏幕
            mFLAction.setVisibility(View.VISIBLE);
            mLayoutTitle.setVisibility(View.VISIBLE);
            setScreenLayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, DisplayUtils.dp2px(this, 424));
        }
    }

    private void setScreenLayoutParams(int width, int height) {
        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(width, height);
        if (width == ViewGroup.LayoutParams.MATCH_PARENT && height == ViewGroup.LayoutParams.MATCH_PARENT) {
            layoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
            layoutParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
            layoutParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
            layoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
        }
        mVideoview.setLayoutParams(layoutParams);
        mVideoview.requestFocus();
    }

    private void playVoice(int voiceID) {
        mMediaPlayer.release();

        if (voiceID != 0) {
            mMediaPlayer = MediaPlayer.create(UIUtils.getContext(), voiceID);
        } else {
            // 正确
            voiceID = Constants.ACTION_CORRECT_VOICE[mRandom.nextInt(3)];
            mMediaPlayer = MediaPlayer.create(UIUtils.getContext(), voiceID);
        }
        mMediaPlayer.start();
    }
}
